package com.wpml.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wpml.common.constant.WareConstant;
import com.wpml.common.exception.CustomException;
import com.wpml.common.util.PageUtils;
import com.wpml.common.util.Query;
import com.wpml.ware.dao.PurchaseDao;
import com.wpml.ware.entity.PurchaseDetailModel;
import com.wpml.ware.entity.PurchaseModel;
import com.wpml.ware.service.PurchaseDetailService;
import com.wpml.ware.service.PurchaseService;
import com.wpml.ware.service.WareSkuService;
import com.wpml.ware.vo.MergeVo;
import com.wpml.ware.vo.PurchaseDoneVo;
import com.wpml.ware.vo.PurchaseItemDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 采购信息(WmsPurchase)表服务实现类
 *
 * @author makejava
 * @since 2020-04-07 12:34:52
 */
@Service
@Slf4j
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseModel> implements PurchaseService {
    @Resource
    PurchaseDetailService detailService;

    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseModel> page = this.page(
                new Query<PurchaseModel>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseModel> page = this.page(
                new Query<PurchaseModel>().getPage(params),
                new QueryWrapper<PurchaseModel>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //1、新建一个
            PurchaseModel purchaseEntity = new PurchaseModel();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(LocalDateTime.now());
            purchaseEntity.setUpdateTime(LocalDateTime.now());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        PurchaseModel byId = this.getById(purchaseId);
        if (Objects.nonNull(byId) && byId.getStatus() != 0 && byId.getStatus() != 1) {
            throw new CustomException("无法合并，采购单状态异常");
        }

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailModel> collect = items.stream().map(i -> {
            PurchaseDetailModel detailEntity = new PurchaseDetailModel();

            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());


        detailService.updateBatchById(collect);

        PurchaseModel purchaseEntity = new PurchaseModel();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(LocalDateTime.now());
        this.updateById(purchaseEntity);
    }

    /**
     * @param ids 采购单id
     */
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseModel> collect = ids.stream()
                .map(this::getById)
                .filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                        item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(LocalDateTime.now());
                }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购项的状态
        collect.forEach((item) -> {
            List<PurchaseDetailModel> entities = detailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailModel> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailModel entity1 = new PurchaseDetailModel();
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        Long id = doneVo.getId();

        //2、改变采购项的状态
        boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailModel> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailModel detailEntity = new PurchaseDetailModel();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                ////3、将成功采购的进行入库
                PurchaseDetailModel entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }

        detailService.updateBatchById(updates);

        //1、改变采购单状态
        PurchaseModel purchaseEntity = new PurchaseModel();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(LocalDateTime.now());
        this.updateById(purchaseEntity);
    }
}
